package com.haoze.nurseapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.dto.CronDescriber;
import com.haoze.common.enumeration.ConstantEnum;
import com.haoze.common.enumeration.StateEnum;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.*;
import com.haoze.nurseapp.aop.NurseLogAop;
import com.haoze.nurseapp.dao.CirculationLogMapper;
import com.haoze.nurseapp.dao.MedicineApplyMapper;
import com.haoze.nurseapp.dao.PatientInHospitalMapper;
import com.haoze.nurseapp.dao.PatientMapper;
import com.haoze.nurseapp.dto.*;
import com.haoze.nurseapp.enumeration.ConstsEnum;
import com.haoze.nurseapp.model.DrugApplyDetailEntity;
import com.haoze.nurseapp.model.DrugApplyMainEntity;
import com.haoze.nurseapp.model.PatientInHospitalEntity;
import com.haoze.nurseapp.service.MedicineApplyService;
import com.haoze.nurseapp.service.feign.NurseService;
import com.haoze.nurseapp.vo.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.apache.kafka.common.utils.CopyOnWriteMap;
import org.quartz.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @author lufq
 * @date 2020/9/17
 */
@Service
public class MedicineApplyServiceImpl implements MedicineApplyService {
    @Autowired
    MedicineApplyMapper medicineApplyMapper;
    @Autowired
    PatientInHospitalMapper patientInHospitalMapper;
    @Autowired
    private NurseService nurseService;

    @Value("${his.url.circulation}")
    private String circulationUrl2;

    private static final Logger log = LoggerFactory.getLogger(NurseLogAop.class);

    /**
     * 患者待领药列表
     *
     * @param wardDeptId
     * @param type
     * @return
     */
    public Result waitMedicineList(String wardDeptId, String type, Integer pageNum, Integer pageSize, String inpatList) {
        //PageHelper.startPage(pageNum,pageSize);
        if (StringUtils.isNotBlank(inpatList)) {
            if ("0".equals(type)) {
                //病区领药
                List<MedicineApplyByInpatVo> medicineList = medicineApplyMapper.queryPatientInfoByWardDeptId(wardDeptId, inpatList.split(","));
                return ResultGenerator.genOkResult(medicineList);
                //getMedicineList(medicineList);
                //按照姓名，床号进行合并
            } else if ("1".equals(type)) {
                //门诊领药
                List<MedicineApplyByInpatVo> medicineList = medicineApplyMapper.outpatientDepartmentWaitMedicineList(wardDeptId, inpatList.split(","));
                return ResultGenerator.genOkResult(medicineList);
            } else if ("2".equals(type)) {
                //处方处理本
                List<PrescriptionMedicineApplyByInpatVo> medicineList = medicineApplyMapper.prescriptionWaitMedicineList(wardDeptId, inpatList.split(","));
                //List<Map<String,Object>> medicineList = medicineApplyMapper.prescriptionWaitMedicineList(wardDeptId,inpatList.split(","));
                return ResultGenerator.genOkResult(medicineList);
            }
        }
        //PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(medicineList);
        return ResultGenerator.genOkResult();
    }

    private void getMedicineList(List<Map<String, Object>> medicineList) {
        if (CollectionUtils.isNotEmpty(medicineList)) {
            for (Map<String, Object> map : medicineList) {

                List<String> freqTimes = new ArrayList<String>();

                //长期医嘱按照频次和执行时间计算领药次数
                if ("1".equals(map.get("orderClass")) && "0".equals(map.get("timeMode"))) {
                    String startTime = map.get("startTime").toString();
                    String currentStartTime = map.get("currentStartTime").toString();
                    String endTime = map.get("endTime").toString();
                    Date startDateTime = DateUtil.stringToDate(startTime, "yyyy-MM-dd HH:mm:ss");
                    Date currentStartDateTime = DateUtil.stringToDate(currentStartTime, "yyyy-MM-dd HH:mm:ss");
                    Date endDateTime = DateUtil.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss");

                    //指定时间执行
                    CronDescriber cronDescriber = JSONObject.parseObject((String) map.get("cronDescriber"), CronDescriber.class);
                    String expression = CronUtil.createCronExpression(cronDescriber, null);
                    CronExpression cronExpression = null;
                    try {
                        cronExpression = new CronExpression(expression);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    startDateTime = cronExpression.getNextValidTimeAfter(startDateTime);
                    if (startDateTime.after(currentStartDateTime) && startDateTime.before(endDateTime)) {
                        freqTimes.add(DateUtil.dateToString(startDateTime, "yyyy-MM-dd HH:mm:ss"));
                    }
                    while (startDateTime.before(endDateTime)) {
                        startDateTime = cronExpression.getNextValidTimeAfter(startDateTime);
                        if (startDateTime.after(currentStartDateTime) && startDateTime.before(endDateTime)) {
                            freqTimes.add(DateUtil.dateToString(startDateTime, "yyyy-MM-dd HH:mm:ss"));
                        }
                    }
                    map.put("freqTimes", CollectionUtils.isNotEmpty(freqTimes) ? StringUtils.join(freqTimes, ",") : "");

                } else if ("1".equals(map.get("orderClass")) && "1".equals(map.get("timeMode"))) {
                    String startTime = map.get("startTime").toString();
                    String currentStartTime = map.get("currentStartTime").toString();
                    String endTime = map.get("endTime").toString();
                    Date startDateTime = DateUtil.stringToDate(startTime, "yyyy-MM-dd HH:mm:ss");
                    Date currentStartDateTime = DateUtil.stringToDate(currentStartTime, "yyyy-MM-dd HH:mm:ss");
                    Date endDateTime = DateUtil.stringToDate(endTime, "yyyy-MM-dd HH:mm:ss");

                    //根据医嘱id获取执行时间
                    String executeTime = medicineApplyMapper.queryExecuteTimeByInpatorderdataId(map.get("inpatorderdataId").toString());
                    //间隔时间执行
                    CronDescriber cronDescriber = JSONObject.parseObject((String) map.get("cronDescriber"), CronDescriber.class);
                    String expression = CronUtil.createCronExpression(cronDescriber, null);
                    CronExpression cronExpression = null;
                    try {
                        cronExpression = new CronExpression(expression);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    //计算开始时间
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(startDateTime);
                    cl.add(Calendar.HOUR_OF_DAY, Integer.parseInt(executeTime));
                    startDateTime = cl.getTime();
                    if (startDateTime.after(currentStartDateTime) && startDateTime.before(endDateTime)) {
                        freqTimes.add(DateUtil.dateToString(startDateTime, "yyyy-MM-dd HH:mm:ss"));
                    }
                    while (startDateTime.before(endDateTime)) {
                        //startDateTime = cronExpression.getNextValidTimeAfter(startDateTime);
                        startDateTime = DateUtil.increasedSeconds(startDateTime, Integer.parseInt((String) map.get("exeCycleStamp")));
                        if (startDateTime.after(currentStartDateTime) && startDateTime.before(endDateTime)) {
                            freqTimes.add(DateUtil.dateToString(startDateTime, "yyyy-MM-dd HH:mm:ss"));
                        }
                    }
                    map.put("freqTimes", CollectionUtils.isNotEmpty(freqTimes) ? StringUtils.join(freqTimes, ",") : "");
                }
                map.put("executivePharmacy", "");
            }
        }
    }

    /**
     * 根据病区id获取药房列表
     *
     * @param wardDeptId
     * @return
     */
    public Result queryPharmacyByWardDeptId(String wardDeptId, String flag) {
        return ResultGenerator.genOkResult(medicineApplyMapper.queryPharmacyByWardDeptId(wardDeptId, flag));
    }

    /**
     * 门诊领药数据检查
     */
    public Result confirmTips(MedicineApplyDTO medicineApplyDTO) {
        String type = medicineApplyDTO.getType();
        String wardDeptId = medicineApplyDTO.getWardDeptId();
        Date date = new Date();
        /*String type = medicineApplyDTO.getType();
        String wardDeptId = medicineApplyDTO.getWardDeptId();
        Date date = new Date();
        if ("0".equals(type)) {
            Set<Integer> set = new HashSet<Integer>();
            //病区领药
            if (StringUtils.isNotBlank(wardDeptId) && CollectionUtils.isEmpty(medicineApplyDTO.getMedicineApplyList())) {
                //常规
                List<Map<String, Object>> medicineList = medicineApplyMapper.wardWaitMedicineList(wardDeptId, medicineApplyDTO.getInpatList().split(","));
                Map<String, List<Map<String, Object>>> collect = medicineList.stream().collect(Collectors.groupingBy(e -> fetchGroupInpatNum(e)));
                for (String key : collect.keySet()) {
                    List<Map<String, Object>> detailList = collect.get(key);
                    for (Map<String, Object> map : detailList) {
                        if ("2".equals(map.get("newOrderFlag")) && map.get("confirmDatetime")!=null && !"".equals(map.get("confirmDatetime"))) {
                            if (!DateUtils.formatDate(date, "yyyy-MM-dd").equals(map.get("confirmDatetime").toString().substring(0, 10))) {
                                set.add(Integer.parseInt(map.get("bedNo").toString()));
                                break;
                            }
                        }
                    }
                }
                if (!set.isEmpty()) {
                    List<Integer> bedNoList = new ArrayList<>(set);
                    Collections.sort(bedNoList);
                    return ResultGenerator.genOkResult(StringUtils.join(bedNoList, ",") + "床医嘱未确认!");
                }
            }
        }*/


        //申请时间
        //获取急诊药房
        if ("1".equals(type)) {
            StringBuffer sb = new StringBuffer();
            String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
            Map<String, String> pharmacyMap = medicineApplyMapper.queryEmergencyPharmacyByWardDeptId(wardDeptId, "1");
            List<MedicineApplyDetailDTO> medicineApplyList = medicineApplyDTO.getMedicineApplyList();
            if (CollectionUtils.isNotEmpty(medicineApplyList)) {
                Map<String, List<MedicineApplyDetailDTO>> collect = medicineApplyList.stream().collect(Collectors.groupingBy(e -> fetchGroupInpatNumAndOrderNo(e)));
                //his对接
                for (String key : collect.keySet()) {
                    String inpatNum = key.split("#")[0];
                    //his对接
                    String orgId = UUIDUtil.randomString();
                    Map<String, Object> param = new HashMap<>();
                    param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
                    param.put("operationdate", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                    param.put("ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(wardDeptId));
                    param.put("performed_by", pharmacyMap.get("deptCode"));
                    param.put("patient_id", inpatNum.split("-")[0]);
                    param.put("visit_id", Integer.parseInt(inpatNum.split("-")[1]));
                    param.put("check_data", "Y");

                    List<Map<String, String>> ordersList = new CopyOnWriteArrayList<>();
                    List<MedicineApplyDetailDTO> detailList = collect.get(key);
                    for (MedicineApplyDetailDTO medicineApplyDetailDTO : detailList) {
                        Map<String, String> reqMap = new HashMap<String, String>();
                        String inpatorderdataId = medicineApplyDetailDTO.getSelectId();
                        Map<String, String> map = medicineApplyMapper.queryTmpPatientOrders(inpatorderdataId);
                        if (map != null) {
                            String primaryId = map.get("primaryId");
                            reqMap.put("primary_id", primaryId);
                        }
                        ordersList.add(reqMap);
                    }
                    param.put("orders", ordersList);

                    Map<String, Object> requestMap = new HashMap<>();
                    requestMap.put("request", param);
                    Map<String, Object> params = new HashMap<>();
                    params.put("c_request", requestMap);
                    params.put("operationID", ConstantEnum.HIS_MEDICINE_APPLY_10007.getKey());
                    System.out.println(JSON.toJSONString(params));
                    JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
                    if (jsonObject.isEmpty()) {
                        return ResultGenerator.genFailedResult("门诊领药数据检查失败");
                    }
                    log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                    Map<String, Object> errorMap = new HashMap<>();
                    if (null != jsonObject) {
                        Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                        if (resInt < 0) {
                            //return ResultGenerator.genOkResult(jsonObject.getString("Error_Msg"));
                            sb.append(jsonObject.getString("Error_Msg") + ";");
                        }
                    }

                }
            }

            if (sb != null && sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
                return ResultGenerator.genOkResult(sb.toString());
            }
        }

        return ResultGenerator.genOkResult();
    }


    /**
     * 保存
     */
    @Transactional(rollbackFor = Exception.class)
    public Result saveMedicineApply(MedicineApplyDTO medicineApplyDTO) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        String type = medicineApplyDTO.getType();
        String wardDeptId = medicineApplyDTO.getWardDeptId();
        Date date = new Date();
        Timestamp currentTime = new Timestamp(date.getTime());
        String nuserCode = patientInHospitalMapper.queryPersonCodeByUserId(userId);
        if ("0".equals(type)) {
            StringBuffer resultMap = new StringBuffer();
            Set<String> set = new HashSet<String>();
            //病区领药
            if ("0".equals(medicineApplyDTO.getWholeWardFlag())) {
                List<Map<String, Object>> medicineList = medicineApplyMapper.wardWaitMedicineList(wardDeptId, medicineApplyDTO.getInpatList().split(","));
                //把未确认的进行过滤
                //medicineList = medicineList.stream().filter(m -> "1".equals(m.get("orderClass"))&& m.get("confirmDatetime")!=null && !"".equals(m.get("confirmDatetime")) && DateUtils.formatDate(date, "yyyy-MM-dd").equals(m.get("confirmDatetime").toString().substring(0, 10))).collect(Collectors.toList());
                getMedicineList(medicineList);

                /*if(CollectionUtils.isEmpty(medicineList)){
                    return ResultGenerator.genFailedResult("没有领药数据!");
                }*/

                Map<String, String> pharmacyMap = medicineApplyMapper.queryEmergencyPharmacyByWardDeptId(wardDeptId, "2");

                DrugApplyMainDTO drugApplyMainEntity = new DrugApplyMainDTO();

                //his对接
                String orgId = UUIDUtil.randomString();
                Map<String, Object> param = new HashMap<>();
                param.put("operator", nuserCode);
                param.put("operationdate", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                param.put("req_nurse", nuserCode);

                List<Map<String, String>> reqList = new CopyOnWriteArrayList<>();
                Map<String, String> reqMap = new HashMap<String, String>();
                reqMap.put("post_date_time", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                //申请类型:0常规/1指定病人
                reqMap.put("req_type", "0");
                reqMap.put("ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(wardDeptId));
                reqMap.put("bed_no", "");
                reqMap.put("dispensary", pharmacyMap.get("deptCode"));
                reqMap.put("org_id", orgId);
                reqList.add(reqMap);
                param.put("req_list", reqList);

                Map<String, Object> requestMap = new HashMap<>();
                requestMap.put("request", param);
                Map<String, Object> params = new HashMap<>();
                params.put("c_request", requestMap);
                params.put("operationID", ConstantEnum.HIS_MEDICINE_APPLY_10005.getKey());
                System.out.println(JSON.toJSONString(params));
                JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
                if (jsonObject.isEmpty()) {
                    return ResultGenerator.genFailedResult("病区常规领药失败");
                }
                log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                if (null != jsonObject) {
                    Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                    if (resInt < 0) {
                        return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                    } else if (resInt == 1) {
                        if (jsonObject.getString("c_response") != null) {
                            Map<String, Object> cresponseMap = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, Object>>() {
                            });
                            Map<String, Object> response = (Map<String, Object>) cresponseMap.get("response");

                            String arrearsMsg = (String) response.get("arrears_msg");
                            String confirmMsg = (String) response.get("confirm_msg");

                            if (StringUtils.isNotBlank(arrearsMsg) && StringUtils.isNotBlank(confirmMsg)) {
                                resultMap.append(arrearsMsg).append(";").append(confirmMsg);
                            } else if (StringUtils.isNotBlank(arrearsMsg)) {
                                resultMap.append(arrearsMsg);
                            } else if (StringUtils.isNotBlank(confirmMsg)) {
                                resultMap.append(confirmMsg);
                            }

                            List<Map<String, Object>> list = (List<Map<String, Object>>) response.get("req_list");
                            if (CollectionUtils.isNotEmpty(list)) {
                                for (Map<String, Object> map : list) {
                                    if (orgId.equals(map.get("org_id"))) {
                                        drugApplyMainEntity.setReqId(map.get("req_id").toString());
                                    }
                                }
                            }
                        }
                    }
                }

                Map<String, String> tmpDrugApplyMainMap = medicineApplyMapper.queryTmpDrugApplyMain(drugApplyMainEntity.getReqId());
                if (tmpDrugApplyMainMap != null) {
                    medicineApplyMapper.updateTmpDrugApplyMain(drugApplyMainEntity.getReqId(), orgId);
                } else {
                    medicineApplyMapper.insertTmpDrugApplyMain(drugApplyMainEntity.getReqId(), orgId);
                }
                //常规

                Map<String, List<Map<String, Object>>> collect = medicineList.stream().collect(Collectors.groupingBy(e -> fetchGroupInpatNum(e)));
                //门诊领药
                //DrugApplyMainDTO drugApplyMainEntity = new DrugApplyMainDTO();
                drugApplyMainEntity.setApplyId(orgId);
                drugApplyMainEntity.initAdd();
                drugApplyMainEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                //申请时间
                drugApplyMainEntity.setApplyTime(currentTime);
                drugApplyMainEntity.setApplyStatus("0");
                drugApplyMainEntity.setType(type);
                //his返回的申请号
                //drugApplyMainEntity.setReqId("");
                drugApplyMainEntity.setApplyPersonId(userId);
                drugApplyMainEntity.setPharmacy(pharmacyMap.get("deptId"));
                drugApplyMainEntity.setWardDeptId(wardDeptId);
                //新增领药申请单主表
                medicineApplyMapper.insertDrugApplyMain(drugApplyMainEntity);

                for (String key : collect.keySet()) {
                    //新增领药申请单详细表
                    List<Map<String, Object>> detailList = collect.get(key);
                    List<DrugApplyDetailEntity> drugApplyDetailEntities = new CopyOnWriteArrayList<>();
                    for (Map<String, Object> map : detailList) {
                        DrugApplyDetailEntity drugApplyDetailEntity = new DrugApplyDetailEntity();
                        drugApplyDetailEntity.setApplyDetailId(UUIDUtil.randomString());
                        drugApplyDetailEntity.initAdd();
                        drugApplyDetailEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                        drugApplyDetailEntity.setApplyId(drugApplyMainEntity.getApplyId());
                        drugApplyDetailEntity.setInpatNum(key);
                        drugApplyDetailEntity.setBedNo(map.get("bedNo").toString());
                        drugApplyDetailEntity.setInpatorderdataId(map.get("inpatorderdataId").toString());
                        drugApplyDetailEntity.setApplyStatus(drugApplyMainEntity.getApplyStatus());
                        drugApplyDetailEntity.setReceiveFreqTime(map.get("freqTimes") == null ? "" : map.get("freqTimes").toString());
                        System.out.println(drugApplyDetailEntity.getReceiveFreqTime());
                        drugApplyDetailEntity.setApplyTime(drugApplyMainEntity.getApplyTime());
                        drugApplyDetailEntities.add(drugApplyDetailEntity);
                    }
                    if (CollectionUtils.isNotEmpty(drugApplyDetailEntities)) {
                        int listSize = drugApplyDetailEntities.size();
                        int toIndex = 100;
                        int keyToken = 0;
                        for (int i = 0; i < drugApplyDetailEntities.size(); i += 100) {
                            if (i + 100 > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                                toIndex = listSize - i;
                            }
                            List newList = drugApplyDetailEntities.subList(i, i + toIndex);
                            medicineApplyMapper.insertDrugApplyDetail(newList);
                        }
                    }
                }
                if (resultMap.length() > 0) {
                    return ResultGenerator.genOkResult(resultMap.toString());
                } else {
                    StringBuffer sb = this.queryPaymentNotice(medicineApplyDTO);
                    if (sb.length() > 0) {
                        return ResultGenerator.genOkResult(sb.toString());
                    }
                }
            }
            if ("1".equals(medicineApplyDTO.getWholeWardFlag())) {
                //按住院号床位领药
                //申请时间
                List<DrugApplyMainDTO> drugApplyMainDTOS = new CopyOnWriteArrayList<>();
                List<Map<String, Object>> reqList = new CopyOnWriteArrayList<>();
                List<Map<String, Object>> medicineList = medicineApplyMapper.wardWaitMedicineList(wardDeptId, medicineApplyDTO.getInpatList().split(","));
                //把未确认的进行过滤
                //medicineList = medicineList.stream().filter(m -> "1".equals(m.get("orderClass"))&& m.get("confirmDatetime")!=null && !"".equals(m.get("confirmDatetime")) && DateUtils.formatDate(date, "yyyy-MM-dd").equals(m.get("confirmDatetime").toString().substring(0, 10))).collect(Collectors.toList());
                getMedicineList(medicineList);

                /*if(CollectionUtils.isEmpty(medicineList)){
                    return ResultGenerator.genFailedResult("没有领药数据!");
                }*/

                if (CollectionUtils.isNotEmpty(medicineList)) {
                    Map<String, Object> param = new HashMap<>();
                    param.put("operator", nuserCode);
                    param.put("operationdate", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                    param.put("req_nurse", nuserCode);

                    Map<String, String> pharmacyMap = medicineApplyMapper.queryEmergencyPharmacyByWardDeptId(wardDeptId, "2");
                    Map<String, List<Map<String, Object>>> collect = medicineList.stream().collect(Collectors.groupingBy(e -> fetchGroupInpatNum(e)));
                    for (String key : collect.keySet()) {
                        //门诊领药
                        DrugApplyMainDTO drugApplyMainEntity = new DrugApplyMainDTO();
                        drugApplyMainEntity.setApplyId(UUIDUtil.randomString());
                        drugApplyMainEntity.initAdd();
                        drugApplyMainEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                        //申请时间
                        drugApplyMainEntity.setApplyTime(currentTime);
                        drugApplyMainEntity.setApplyStatus("0");
                        drugApplyMainEntity.setType(type);
                        //his返回的申请号
                        //drugApplyMainEntity.setReqId("");
                        drugApplyMainEntity.setApplyPersonId(userId);
                        drugApplyMainEntity.setPharmacy(pharmacyMap.get("deptId"));
                        drugApplyMainEntity.setInpatNum(key);
                        drugApplyMainEntity.setBedNo(collect.get(key).get(0).get("bedNo").toString());
                        drugApplyMainEntity.setWardDeptId(wardDeptId);
                        //新增领药申请单主表
                        //medicineApplyMapper.insertDrugApplyMain(drugApplyMainEntity);
                        //新增领药申请单详细表
                        List<Map<String, Object>> detailList = collect.get(key);
                        List<DrugApplyDetailEntity> drugApplyDetailEntities = new CopyOnWriteArrayList<>();
                        for (Map<String, Object> map : detailList) {
                            DrugApplyDetailEntity drugApplyDetailEntity = new DrugApplyDetailEntity();
                            drugApplyDetailEntity.setApplyDetailId(UUIDUtil.randomString());
                            drugApplyDetailEntity.initAdd();
                            drugApplyDetailEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                            drugApplyDetailEntity.setApplyId(drugApplyMainEntity.getApplyId());
                            drugApplyDetailEntity.setInpatNum(key);
                            drugApplyDetailEntity.setBedNo(map.get("bedNo").toString());
                            drugApplyDetailEntity.setInpatorderdataId(map.get("inpatorderdataId").toString());
                            drugApplyDetailEntity.setApplyStatus(drugApplyMainEntity.getApplyStatus());
                            drugApplyDetailEntity.setReceiveFreqTime(map.get("freqTimes") == null ? "" : map.get("freqTimes").toString());
                            drugApplyDetailEntity.setApplyTime(drugApplyMainEntity.getApplyTime());
                            drugApplyDetailEntities.add(drugApplyDetailEntity);
                        }
                    /*if(CollectionUtils.isNotEmpty(drugApplyDetailEntities)){
                        medicineApplyMapper.insertDrugApplyDetail(drugApplyDetailEntities);
                    }*/
                        drugApplyMainEntity.setDrugApplyDetailEntityList(drugApplyDetailEntities);
                        drugApplyMainDTOS.add(drugApplyMainEntity);
                        Map<String, Object> reqMap = new HashMap<String, Object>();
                        reqMap.put("post_date_time", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                        //申请类型:0常规/1指定病人
                        reqMap.put("req_type", "1");
                        reqMap.put("ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(wardDeptId));
                        reqMap.put("bed_no", Integer.parseInt(drugApplyMainEntity.getBedNo()));
                        reqMap.put("dispensary", pharmacyMap.get("deptCode"));
                        reqMap.put("org_id", drugApplyMainEntity.getApplyId());
                        reqList.add(reqMap);
                    }
                    param.put("req_list", reqList);

                    Map<String, Object> requestMap = new HashMap<>();
                    requestMap.put("request", param);
                    Map<String, Object> params = new HashMap<>();
                    params.put("c_request", requestMap);
                    params.put("operationID", ConstantEnum.HIS_MEDICINE_APPLY_10005.getKey());
                    System.out.println(JSON.toJSONString(params));
                    JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
                    if (jsonObject.isEmpty()) {
                        return ResultGenerator.genFailedResult("病区指定人领药失败");
                    }
                    log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                    if (null != jsonObject) {
                        Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                        if (resInt < 0) {
                            return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                        } else if (resInt == 1) {
                            if (jsonObject.getString("c_response") != null) {
                                //Map c_response = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, String>(){});
                                //c_response.get("response");
                                Map<String, Object> cresponseMap = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, Object>>() {
                                });
                                Map<String, Object> response = (Map<String, Object>) cresponseMap.get("response");

                                String arrearsMsg = (String) response.get("arrears_msg");
                                String confirmMsg = (String) response.get("confirm_msg");

                                if (StringUtils.isNotBlank(arrearsMsg) && StringUtils.isNotBlank(confirmMsg)) {
                                    resultMap.append(arrearsMsg).append(";").append(confirmMsg);
                                } else if (StringUtils.isNotBlank(arrearsMsg)) {
                                    resultMap.append(arrearsMsg);
                                } else if (StringUtils.isNotBlank(confirmMsg)) {
                                    resultMap.append(confirmMsg);
                                }

                                List<Map<String, Object>> list = (List<Map<String, Object>>) response.get("req_list");
                                if (CollectionUtils.isNotEmpty(list)) {
                                    for (Map<String, Object> map : list) {
                                        for (DrugApplyMainDTO drugApplyMainDTO : drugApplyMainDTOS) {
                                            if (drugApplyMainDTO.getApplyId().equals(map.get("org_id"))) {
                                                drugApplyMainDTO.setReqId(map.get("req_id").toString());
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (CollectionUtils.isNotEmpty(drugApplyMainDTOS)) {

                        for (DrugApplyMainDTO drugApplyMainDTO : drugApplyMainDTOS) {

                            Map<String, String> tmpDrugApplyMainMap = medicineApplyMapper.queryTmpDrugApplyMain(drugApplyMainDTO.getReqId());
                            if (tmpDrugApplyMainMap != null) {
                                medicineApplyMapper.updateTmpDrugApplyMain(drugApplyMainDTO.getReqId(), drugApplyMainDTO.getApplyId());
                            } else {
                                medicineApplyMapper.insertTmpDrugApplyMain(drugApplyMainDTO.getReqId(), drugApplyMainDTO.getApplyId());
                            }
                            medicineApplyMapper.insertDrugApplyMain(drugApplyMainDTO);
                            if (CollectionUtils.isNotEmpty(drugApplyMainDTO.getDrugApplyDetailEntityList())) {
                                //medicineApplyMapper.insertDrugApplyDetail(drugApplyMainDTO.getDrugApplyDetailEntityList());
                                int listSize = drugApplyMainDTO.getDrugApplyDetailEntityList().size();
                                int toIndex = 100;
                                int keyToken = 0;
                                for (int i = 0; i < drugApplyMainDTO.getDrugApplyDetailEntityList().size(); i += 100) {
                                    if (i + 100 > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                                        toIndex = listSize - i;
                                    }
                                    List newList = drugApplyMainDTO.getDrugApplyDetailEntityList().subList(i, i + toIndex);
                                    medicineApplyMapper.insertDrugApplyDetail(newList);
                                }
                            }
                        }
                    }
                    if (resultMap.length() > 0) {
                        return ResultGenerator.genOkResult(resultMap.toString());
                    } else {
                        StringBuffer sb = this.queryPaymentNotice(medicineApplyDTO);
                        if (sb.length() > 0) {
                            return ResultGenerator.genOkResult(sb.toString());
                        }
                    }
                } else {
                    String[] inpatNums = medicineApplyDTO.getInpatList().split(",");
                    Map<String, String> pharmacyMap = medicineApplyMapper.queryEmergencyPharmacyByWardDeptId(wardDeptId, "2");
                    Map<String, Object> param = new HashMap<>();
                    param.put("operator", nuserCode);
                    param.put("operationdate", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                    param.put("req_nurse", nuserCode);
                    for (String inpatNum : inpatNums) {
                        //门诊领药
                        DrugApplyMainDTO drugApplyMainEntity = new DrugApplyMainDTO();
                        drugApplyMainEntity.setApplyId(UUIDUtil.randomString());
                        drugApplyMainEntity.initAdd();
                        drugApplyMainEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                        //申请时间
                        drugApplyMainEntity.setApplyTime(currentTime);
                        drugApplyMainEntity.setApplyStatus("0");
                        drugApplyMainEntity.setType(type);
                        //his返回的申请号
                        //drugApplyMainEntity.setReqId("");
                        drugApplyMainEntity.setApplyPersonId(userId);
                        drugApplyMainEntity.setPharmacy(pharmacyMap.get("deptId"));
                        drugApplyMainEntity.setInpatNum(inpatNum);
                        drugApplyMainEntity.setBedNo(medicineApplyMapper.queryPatientInHospitalByInpatNum(inpatNum));
                        drugApplyMainEntity.setWardDeptId(wardDeptId);
                        drugApplyMainDTOS.add(drugApplyMainEntity);

                        Map<String, Object> reqMap = new HashMap<String, Object>();
                        reqMap.put("post_date_time", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                        //申请类型:0常规/1指定病人
                        reqMap.put("req_type", "1");
                        reqMap.put("ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(wardDeptId));
                        reqMap.put("bed_no", Integer.parseInt(drugApplyMainEntity.getBedNo()));
                        reqMap.put("dispensary", pharmacyMap.get("deptCode"));
                        reqMap.put("org_id", drugApplyMainEntity.getApplyId());
                        reqList.add(reqMap);

                    }
                    param.put("req_list", reqList);

                    Map<String, Object> requestMap = new HashMap<>();
                    requestMap.put("request", param);
                    Map<String, Object> params = new HashMap<>();
                    params.put("c_request", requestMap);
                    params.put("operationID", ConstantEnum.HIS_MEDICINE_APPLY_10005.getKey());
                    System.out.println(JSON.toJSONString(params));
                    JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
                    if (jsonObject.isEmpty()) {
                        return ResultGenerator.genFailedResult("病区指定人领药失败");
                    }
                    log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                    if (null != jsonObject) {
                        Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                        if (resInt < 0) {
                            return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                        } else if (resInt == 1) {
                            if (jsonObject.getString("c_response") != null) {
                                //Map c_response = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, String>(){});
                                //c_response.get("response");
                                Map<String, Object> cresponseMap = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, Object>>() {
                                });
                                Map<String, Object> response = (Map<String, Object>) cresponseMap.get("response");

                                String arrearsMsg = (String) response.get("arrears_msg");
                                String confirmMsg = (String) response.get("confirm_msg");

                                if (StringUtils.isNotBlank(arrearsMsg) && StringUtils.isNotBlank(confirmMsg)) {
                                    resultMap.append(arrearsMsg).append(";").append(confirmMsg);
                                } else if (StringUtils.isNotBlank(arrearsMsg)) {
                                    resultMap.append(arrearsMsg);
                                } else if (StringUtils.isNotBlank(confirmMsg)) {
                                    resultMap.append(confirmMsg);
                                }

                                List<Map<String, Object>> list = (List<Map<String, Object>>) response.get("req_list");
                                if (CollectionUtils.isNotEmpty(list)) {
                                    for (Map<String, Object> map : list) {
                                        for (DrugApplyMainDTO drugApplyMainDTO : drugApplyMainDTOS) {
                                            if (drugApplyMainDTO.getApplyId().equals(map.get("org_id"))) {
                                                drugApplyMainDTO.setReqId(map.get("req_id").toString());
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (CollectionUtils.isNotEmpty(drugApplyMainDTOS)) {
                            for (DrugApplyMainDTO drugApplyMainDTO : drugApplyMainDTOS) {
                                Map<String, String> tmpDrugApplyMainMap = medicineApplyMapper.queryTmpDrugApplyMain(drugApplyMainDTO.getReqId());
                                if (tmpDrugApplyMainMap != null) {
                                    medicineApplyMapper.updateTmpDrugApplyMain(drugApplyMainDTO.getReqId(), drugApplyMainDTO.getApplyId());
                                } else {
                                    medicineApplyMapper.insertTmpDrugApplyMain(drugApplyMainDTO.getReqId(), drugApplyMainDTO.getApplyId());
                                }
                                medicineApplyMapper.insertDrugApplyMain(drugApplyMainDTO);
                            }
                        }
                        if (resultMap.length() > 0) {
                            return ResultGenerator.genOkResult(resultMap.toString());
                        } else {
                            StringBuffer sb = this.queryPaymentNotice(medicineApplyDTO);
                            if (sb.length() > 0) {
                                return ResultGenerator.genOkResult(sb.toString());
                            }
                        }
                    }
                }
            }
        } else if ("1".equals(type)) {
            StringBuffer sb = new StringBuffer();
            List<DrugApplyMainDTO> drugApplyMainDTOS = new CopyOnWriteArrayList<>();
            //获取急诊药房
            Map<String, String> pharmacyMap = medicineApplyMapper.queryEmergencyPharmacyByWardDeptId(wardDeptId, "1");
            String nurseCode = patientInHospitalMapper.queryPersonCodeByUserId(userId);
            String wardCode = patientInHospitalMapper.queryDeptCodeByDeptId(wardDeptId);
            List<MedicineApplyDetailDTO> medicineApplyList = medicineApplyDTO.getMedicineApplyList();
            if (CollectionUtils.isNotEmpty(medicineApplyList)) {
                Map<String, List<MedicineApplyDetailDTO>> collect = medicineApplyList.stream().collect(Collectors.groupingBy(e -> fetchGroupKey(e)));
                //his对接
                for (String key : collect.keySet()) {
                    String inpatNum = key;
                    //门诊领药
                    //his对接
                    Map<String, Object> param = new HashMap<>();
                    param.put("operator", nurseCode);
                    param.put("operationdate", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                    param.put("ward_code", wardCode);
                    param.put("performed_by", pharmacyMap.get("deptCode"));
                    param.put("patient_id", inpatNum.split("-")[0]);
                    param.put("visit_id", Integer.parseInt(inpatNum.split("-")[1]));
                    param.put("check_data", "N");

                    DrugApplyMainDTO drugApplyMainEntity = new DrugApplyMainDTO();
                    drugApplyMainEntity.setApplyId(UUIDUtil.randomString());
                    drugApplyMainEntity.initAdd();
                    drugApplyMainEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                    //申请时间
                    drugApplyMainEntity.setApplyTime(currentTime);
                    drugApplyMainEntity.setApplyStatus("0");
                    drugApplyMainEntity.setType(type);
                    //his返回的申请号
                    //drugApplyMainEntity.setReqId("");
                    drugApplyMainEntity.setApplyPersonId(userId);
                    drugApplyMainEntity.setPharmacy(pharmacyMap.get("deptId"));
                    drugApplyMainEntity.setInpatNum(inpatNum);
                    drugApplyMainEntity.setBedNo(collect.get(key).get(0).getBedNo());
                    drugApplyMainEntity.setWardDeptId(wardDeptId);
                    //新增领药申请单主表
                    //medicineApplyMapper.insertDrugApplyMain(drugApplyMainEntity);
                    //新增领药申请单详细表
                    List<MedicineApplyDetailDTO> detailList = collect.get(key);
                    List<DrugApplyDetailEntity> drugApplyDetailEntities = new CopyOnWriteArrayList<>();
                    for (MedicineApplyDetailDTO medicineApplyDetailDTO : detailList) {
                        DrugApplyDetailEntity drugApplyDetailEntity = new DrugApplyDetailEntity();
                        drugApplyDetailEntity.setApplyDetailId(UUIDUtil.randomString());
                        drugApplyDetailEntity.initAdd();
                        drugApplyDetailEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                        drugApplyDetailEntity.setApplyId(drugApplyMainEntity.getApplyId());
                        drugApplyDetailEntity.setInpatNum(drugApplyMainEntity.getInpatNum());
                        drugApplyDetailEntity.setBedNo(drugApplyMainEntity.getBedNo());
                        drugApplyDetailEntity.setInpatorderdataId(medicineApplyDetailDTO.getSelectId());
                        drugApplyDetailEntity.setApplyStatus(drugApplyMainEntity.getApplyStatus());
                        drugApplyDetailEntity.setApplyTime(drugApplyMainEntity.getApplyTime());
                        drugApplyDetailEntities.add(drugApplyDetailEntity);
                    }
                    drugApplyMainEntity.setDrugApplyDetailEntityList(drugApplyDetailEntities);
                    /*if(CollectionUtils.isNotEmpty(drugApplyDetailEntities)){
                        medicineApplyMapper.insertDrugApplyDetail(drugApplyDetailEntities);
                    }*/


                    List<Map<String, String>> ordersList = new CopyOnWriteArrayList<>();
                    for (DrugApplyDetailEntity drugEntity : drugApplyDetailEntities) {
                        Map<String, String> reqMap = new HashMap<String, String>();
                        String inpatorderdataId = drugEntity.getInpatorderdataId();
                        Map<String, String> map = medicineApplyMapper.queryTmpPatientOrders(inpatorderdataId);
                        if (map != null) {
                            String primaryId = map.get("primaryId");
                            reqMap.put("primary_id", primaryId);
                            reqMap.put("org_id", drugEntity.getApplyDetailId());
                        }
                        ordersList.add(reqMap);
                    }
                    param.put("orders", ordersList);

                    Map<String, Object> requestMap = new HashMap<>();
                    requestMap.put("request", param);
                    Map<String, Object> params = new HashMap<>();
                    params.put("c_request", requestMap);
                    params.put("operationID", ConstantEnum.HIS_MEDICINE_APPLY_10007.getKey());
                    System.out.println(JSON.toJSONString(params));
                    JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
                    if (jsonObject.isEmpty()) {
                        return ResultGenerator.genFailedResult("门诊领药申请失败");
                    }
                    log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                    if (null != jsonObject) {
                        Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                        if (resInt < 0) {
                            return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                        } else if (resInt == 1) {
                            if (jsonObject.getString("c_response") != null) {
                                //Map c_response = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, String>(){});
                                //c_response.get("response");
                                Map<String, Object> cresponseMap = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, Object>>() {
                                });
                                Map<String, Object> response = (Map<String, Object>) cresponseMap.get("response");

                                List<Map<String, Object>> list = (List<Map<String, Object>>) response.get("presc");
                                if (CollectionUtils.isNotEmpty(list)) {
                                    for (Map<String, Object> map : list) {
                                        drugApplyMainEntity.setReqId(map.get("presc_no").toString());
                                    }
                                }
                            }
                            drugApplyMainDTOS.add(drugApplyMainEntity);
                        }
                    }

                }

                //新增数据
                if (CollectionUtils.isNotEmpty(drugApplyMainDTOS)) {
                    for (DrugApplyMainDTO drugApplyMainDTO : drugApplyMainDTOS) {
                        medicineApplyMapper.insertDrugApplyMain(drugApplyMainDTO);
                        if (CollectionUtils.isNotEmpty(drugApplyMainDTO.getDrugApplyDetailEntityList())) {
                            //medicineApplyMapper.insertDrugApplyDetail(drugApplyMainDTO.getDrugApplyDetailEntityList());
                            int listSize = drugApplyMainDTO.getDrugApplyDetailEntityList().size();
                            int toIndex = 100;
                            for (int i = 0; i < drugApplyMainDTO.getDrugApplyDetailEntityList().size(); i += 100) {
                                if (i + 100 > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                                    toIndex = listSize - i;
                                }
                                List newList = drugApplyMainDTO.getDrugApplyDetailEntityList().subList(i, i + toIndex);
                                medicineApplyMapper.insertDrugApplyDetail(newList);
                            }
                        }
                    }
                }
                if (sb.length() > 0) {
                    sb.deleteCharAt(sb.length() - 1);
                    return ResultGenerator.genFailedResult(sb.toString());
                } else {
                    StringBuffer sb2 = this.queryPaymentNotice(medicineApplyDTO);
                    if (sb2.length() > 0) {
                        return ResultGenerator.genOkResult(sb2.toString());
                    }
                }
            }

        } else if ("2".equals(type)) {
            String nurseCode = patientInHospitalMapper.queryPersonCodeByUserId(userId);
            String wardCode = patientInHospitalMapper.queryDeptCodeByDeptId(wardDeptId);
            List<DrugApplyMainDTO> drugApplyMainDTOS = new CopyOnWriteArrayList<>();
            //处方处理本
            //申请时间
            List<MedicineApplyDetailDTO> medicineApplyList = medicineApplyDTO.getMedicineApplyList();
            if (CollectionUtils.isNotEmpty(medicineApplyList)) {
                //判断皮试
                for (MedicineApplyDetailDTO medicineApplyDetailDTO : medicineApplyList) {
                    Map<String, String> map = medicineApplyMapper.queryPatientPrescDrugInfo(medicineApplyDetailDTO.getSelectId());
                    if (map != null) {
                        if (StringUtils.isNotBlank(map.get("testDrugFlag"))
                                && "1".equals(map.get("testDrugFlag"))
                                && (map.get("testDrug") == null || "皮试".equals(map.get("testDrug")))
                                && "".equals(medicineApplyDetailDTO.getPerformResult())) {
                            return ResultGenerator.genFailedResult("请输入" + map.get("drugName") + "皮试结果后再保存!");
                        } else if (StringUtils.isNotBlank(map.get("testDrugFlag"))
                                && "1".equals(map.get("testDrugFlag"))
                                && (map.get("testDrug") == null || "皮试".equals(map.get("testDrug")))
                                && "(+)".equals(medicineApplyDetailDTO.getPerformResult())) {
                            return ResultGenerator.genFailedResult(map.get("drugName") + "皮试为阳性,请通知医师修改处方!");
                        }
                    }
                }

                Map<String, List<MedicineApplyDetailDTO>> collect = medicineApplyList.stream().collect(Collectors.groupingBy(e -> fetchGroupInpatNumAndPrescId(e)));
                //his对接
                for (String key : collect.keySet()) {
                    String inputNum = key.split("#")[0];
                    String prescId = key.split("#")[1];

                    Map<String, Object> param = new HashMap<>();
                    param.put("operator", nurseCode);
                    param.put("operationdate", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                    param.put("ward_code", wardCode);
                    param.put("patient_id", inputNum.split("-")[0]);
                    param.put("visit_id", Integer.parseInt(inputNum.split("-")[1]));

                    //门诊领药
                    DrugApplyMainDTO drugApplyMainEntity = new DrugApplyMainDTO();
                    drugApplyMainEntity.setApplyId(UUIDUtil.randomString());
                    drugApplyMainEntity.initAdd();
                    drugApplyMainEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                    //申请时间
                    drugApplyMainEntity.setApplyTime(currentTime);
                    drugApplyMainEntity.setApplyStatus("0");
                    drugApplyMainEntity.setType(type);
                    //his返回的申请号
                    drugApplyMainEntity.setReqId(collect.get(key).get(0).getPrescNum());
                    drugApplyMainEntity.setApplyPersonId(userId);
                    drugApplyMainEntity.setPharmacy(collect.get(key).get(0).getPharmacyId());
                    drugApplyMainEntity.setInpatNum(inputNum);
                    drugApplyMainEntity.setBedNo(collect.get(key).get(0).getBedNo());
                    drugApplyMainEntity.setWardDeptId(wardDeptId);
                    drugApplyMainEntity.setPrescId(prescId);
                    //新增领药申请单主表
                    //medicineApplyMapper.insertDrugApplyMain(drugApplyMainEntity);
                    //新增领药申请单详细表
                    List<MedicineApplyDetailDTO> detailList = collect.get(key);
                    List<DrugApplyDetailEntity> drugApplyDetailEntities = new CopyOnWriteArrayList<>();
                    //Set<String> prescNumSet = new HashSet<String>();
                    List<Map<String, String>> prescDetail = new ArrayList<Map<String, String>>();
                    for (MedicineApplyDetailDTO medicineApplyDetailDTO : detailList) {
                        DrugApplyDetailEntity drugApplyDetailEntity = new DrugApplyDetailEntity();
                        drugApplyDetailEntity.setApplyDetailId(UUIDUtil.randomString());
                        drugApplyDetailEntity.initAdd();
                        drugApplyDetailEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                        drugApplyDetailEntity.setApplyId(drugApplyMainEntity.getApplyId());
                        drugApplyDetailEntity.setInpatNum(drugApplyMainEntity.getInpatNum());
                        drugApplyDetailEntity.setBedNo(drugApplyMainEntity.getBedNo());
                        drugApplyDetailEntity.setPrescdrugId(medicineApplyDetailDTO.getSelectId());
                        drugApplyDetailEntity.setPrescNum(medicineApplyDetailDTO.getPrescNum());
                        drugApplyDetailEntity.setApplyStatus(drugApplyMainEntity.getApplyStatus());
                        drugApplyDetailEntity.setApplyTime(drugApplyMainEntity.getApplyTime());
                        drugApplyDetailEntity.setPerformResult(medicineApplyDetailDTO.getPerformResult());
                        drugApplyDetailEntities.add(drugApplyDetailEntity);
                        //prescNumSet.add(medicineApplyDetailDTO.getPrescId());
                        Map<String, String> map = medicineApplyMapper.queryTmpPatientPrescDrug(medicineApplyDetailDTO.getSelectId());
                        if (map != null) {
                            map.put("ps_result", medicineApplyDetailDTO.getPerformResult());
                        }
                        prescDetail.add(map);
                    }
                    drugApplyMainEntity.setDrugApplyDetailEntityList(drugApplyDetailEntities);

                    List<Map<String, String>> prescMaster = medicineApplyMapper.queryTmpPatientPresc(prescId);
                    Map<String, Object> prescMap = new HashMap<>();
                    prescMap.put("presc_master", prescMaster);
                    prescMap.put("presc_detail", prescDetail);

                    param.put("presc", prescMap);

                    Map<String, Object> requestMap = new HashMap<>();
                    requestMap.put("request", param);
                    Map<String, Object> params = new HashMap<>();
                    params.put("c_request", requestMap);
                    params.put("operationID", ConstantEnum.HIS_MEDICINE_APPLY_10009.getKey());
                    System.out.println(JSON.toJSONString(params));
                    JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
                    if (jsonObject.isEmpty()) {
                        return ResultGenerator.genFailedResult("处方处理本领药申请失败");
                    }
                    log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                    if (null != jsonObject) {
                        Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                        if (resInt < 0) {
                            return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                        }
                    }

                    drugApplyMainDTOS.add(drugApplyMainEntity);

                    /*if(CollectionUtils.isNotEmpty(drugApplyDetailEntities)){
                        medicineApplyMapper.insertDrugApplyDetail(drugApplyDetailEntities);
                    }*/
                }
                //新增数据
                if (CollectionUtils.isNotEmpty(drugApplyMainDTOS)) {
                    for (DrugApplyMainDTO drugApplyMainDTO : drugApplyMainDTOS) {
                        medicineApplyMapper.insertDrugApplyMain(drugApplyMainDTO);
                        if (CollectionUtils.isNotEmpty(drugApplyMainDTO.getDrugApplyDetailEntityList())) {
                            //medicineApplyMapper.insertDrugApplyDetail(drugApplyMainDTO.getDrugApplyDetailEntityList());
                            int listSize = drugApplyMainDTO.getDrugApplyDetailEntityList().size();
                            int toIndex = 100;
                            for (int i = 0; i < drugApplyMainDTO.getDrugApplyDetailEntityList().size(); i += 100) {
                                if (i + 100 > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                                    toIndex = listSize - i;
                                }
                                List newList = drugApplyMainDTO.getDrugApplyDetailEntityList().subList(i, i + toIndex);
                                medicineApplyMapper.insertDrugApplyDetail(newList);
                            }
                        }
                    }
                }
            }
        }
        return ResultGenerator.genOkResult();

    }

    private StringBuffer queryPaymentNotice(MedicineApplyDTO medicineApplyDTO) {
        StringBuffer sb = new StringBuffer();
        StringBuffer qftysb = new StringBuffer();
        StringBuffer yzqrsb = new StringBuffer();
        Arrays.stream(medicineApplyDTO.getInpatList().split(",")).forEach(inpatNum -> {
            Result result = nurseService.queryPatientPaymentNotice(medicineApplyDTO.getWardDeptId(), inpatNum);
            List<Map> list = JSON.parseArray(JSON.toJSONString(result.getData()), Map.class);
            if (list.size() > 0) {
                Map map = list.get(0);
                if (ConstsEnum.DEFAULT_YES.getIndex().equals(map.get("medicineQuotaFlag"))) {
                    qftysb.append(",").append(map.get("bedNo"));
                }
                if ("01".equals(map.get("deptArea"))) {
                    if ((Integer) map.get("confirmAmt") != 0) {
                        yzqrsb.append(",").append(map.get("bedNo"));
                    }
                }

            }
        });
        if (yzqrsb.length() > 0) {
            sb.append("以下床位患者医嘱未确认：").append(yzqrsb.toString().substring(1));
        }
        if (qftysb.length() > 0) {
            if (sb.length() > 0) {
                sb.append(";");
            }
            sb.append("以下床位患者欠费停药：").append(qftysb.toString().substring(1));
        }
        return sb;
    }

    public Result queryToBeReceivedMedicineList(String type, String wardDeptId, String inpatList, Integer pageNum, Integer pageSize, String pharmacy) {
        //List<Map<String, Object>> medicineList1=new ArrayList<>();
        //PageHelper.startPage(pageNum,pageSize);
        if ("0".equals(type)) {
            //病区领药
            List<ReceiveMedicineApplyByInpatVo> medicineList = medicineApplyMapper.wardToBeReceivedMedicineList(wardDeptId);
            return ResultGenerator.genOkResult(medicineList);
        } else if ("1".equals(type)) {
            //门诊领药
            //medicineList1 = medicineApplyMapper.outpatientDepartmentToBeReceivedMedicineList(wardDeptId);
            if (StringUtils.isNotBlank(inpatList)) {
                List<OutpatientReceiveMedicineApplyByInpatVo> medicineList = medicineApplyMapper.outpatientDepartmentToBeReceivedMedicineList(wardDeptId, inpatList.split(","));
                return ResultGenerator.genOkResult(medicineList);
            }
        } else if ("2".equals(type)) {
            //处方处理本
            if (StringUtils.isNotBlank(inpatList)) {
                List<PrescriptionReceivedMedicineApplyByInpatVo> medicineList = medicineApplyMapper.prescriptionToBeReceivedMedicineList(wardDeptId, pharmacy, inpatList.split(","));
                return ResultGenerator.genOkResult(medicineList);
            }
        }
        //PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(medicineList1);
        return ResultGenerator.genOkResult();
    }


    @Transactional(rollbackFor = Exception.class)
    public Result deleteMedicineApply(String applyIdList, String type) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
        String applys[] = applyIdList.split(",");
        HashSet<String> applySets = new HashSet<>(Arrays.asList(applys));
        List<String> applyIds = new ArrayList<>(applySets);
        if (applyIds != null && applyIds.size() > 0) {
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            List<Map<String, Object>> reqList = new CopyOnWriteArrayList<>();
            //病区领药、处方处理本
            List<DrugApplyMainEntity> drugApplyMainEntities = null;
            //门诊领药
            List<DrugApplyDetailDTO> drugApplyDetailEntities = null;
            if ("0".equals(type) || "2".equals(type)) {
                drugApplyMainEntities = medicineApplyMapper.queryDrugApplyMainList(applyIds);
            } else if ("1".equals(type)) {
                drugApplyDetailEntities = medicineApplyMapper.queryDrugApplyDetailListByInpatorderdataId(applyIds);
            }
            if (CollectionUtils.isNotEmpty(drugApplyMainEntities)) {
                if ("0".equals(type)) {
                    for (DrugApplyMainEntity drugApplyMainEntity : drugApplyMainEntities) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("req_id", Integer.parseInt(drugApplyMainEntity.getReqId()));
                        reqList.add(map);
                    }
                    //病区领药
                    Map<String, Object> param = new HashMap<>();
                    String nuserCode = patientInHospitalMapper.queryPersonCodeByUserId(userId);
                    param.put("operator", nuserCode);
                    param.put("operationdate", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                    param.put("req_list", reqList);
                    Map<String, Object> requestMap = new HashMap<>();
                    requestMap.put("request", param);
                    Map<String, Object> params = new HashMap<>();
                    params.put("c_request", requestMap);
                    params.put("operationID", ConstantEnum.HIS_MEDICINE_APPLY_10006.getKey());
                    System.out.println(JSON.toJSONString(params));
                    JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
                    if (jsonObject.isEmpty()) {
                        return ResultGenerator.genFailedResult("病区领药删除失败");
                    }
                    log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                    if (null != jsonObject) {
                        Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                        if (resInt < 0) {
                            return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                        }
                    }
                } else if ("2".equals(type)) {
                    String nuserCode = patientInHospitalMapper.queryPersonCodeByUserId(userId);
                    for (DrugApplyMainEntity drugApplyMainEntity : drugApplyMainEntities) {
                        //门诊领药
                        Map<String, Object> param = new HashMap<>();
                        param.put("operator", nuserCode);
                        param.put("operationdate", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                        param.put("ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(drugApplyMainEntity.getWardDeptId()));
                        param.put("performed_by", medicineApplyMapper.queryPharmacyCodeById(drugApplyMainEntity.getPharmacy()));
                        param.put("patient_id", drugApplyMainEntity.getInpatNum().split("-")[0]);
                        param.put("visit_id", Integer.parseInt(drugApplyMainEntity.getInpatNum().split("-")[1]));
                        DrugApplyMainEntity drugApplyMainInfo = medicineApplyMapper.queryDrugApplyMainInfo(drugApplyMainEntity.getApplyId());
                        List<Map<String, String>> prescMaster = new ArrayList<>();
                        if (drugApplyMainInfo != null) {
                            prescMaster = medicineApplyMapper.queryTmpPatientPresc2(drugApplyMainInfo.getPrescId());
                        }
                        Map<String, Object> prescMap = new HashMap<String, Object>();
                        prescMap.put("presc_master", prescMaster);
                        param.put("presc", prescMap);

                        Map<String, Object> requestMap = new HashMap<>();
                        requestMap.put("request", param);
                        Map<String, Object> params = new HashMap<>();
                        params.put("c_request", requestMap);
                        params.put("operationID", ConstantEnum.HIS_MEDICINE_APPLY_10010.getKey());
                        System.out.println(JSON.toJSONString(params));
                        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
                        if (jsonObject.isEmpty()) {
                            return ResultGenerator.genFailedResult("处方处理本领药删除失败");
                        }
                        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                        if (null != jsonObject) {
                            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                            if (resInt < 0) {
                                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                            }
                        }
                    }

                }
                //逻辑删除
                for (DrugApplyMainEntity drugApplyMainEntity : drugApplyMainEntities) {
                    drugApplyMainEntity.setDeletePersonId(userId);
                    drugApplyMainEntity.setDeleteTime(timestamp);
                    drugApplyMainEntity.setApplyStatus("3");
                    medicineApplyMapper.updateDrugApplyMain(drugApplyMainEntity);
                    medicineApplyMapper.updateDrugApplyDetail(drugApplyMainEntity.getApplyId(), "3");
                }
            }

            if (CollectionUtils.isNotEmpty(drugApplyDetailEntities)) {
                if ("1".equals(type)) {
                    String nuserCode = patientInHospitalMapper.queryPersonCodeByUserId(userId);

                    //根据住院号和医嘱id分组
                    Map<String, List<DrugApplyDetailDTO>> collect = drugApplyDetailEntities.stream().collect(Collectors.groupingBy(e -> fetchGroupInpatNums(e)));

                    for (String key : collect.keySet()) {
                        //门诊领药
                        Map<String, Object> param = new HashMap<>();
                        param.put("operator", nuserCode);
                        param.put("operationdate", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                        param.put("ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(collect.get(key).get(0).getWardDeptId()));
                        param.put("performed_by", medicineApplyMapper.queryPharmacyCodeById(collect.get(key).get(0).getPharmacy()));
                        param.put("patient_id", key.split("-")[0]);
                        param.put("visit_id", Integer.parseInt(key.split("-")[1]));

                        List<DrugApplyDetailDTO> drugApplyDetailList = collect.get(key);
                        //List<DrugApplyDetailEntity> drugApplyDetailList = medicineApplyMapper.queryDrugApplyDetailList(drugApplyMainEntity.getApplyId());
                        List<Map<String, String>> ordersList = new CopyOnWriteArrayList<>();
                        for (DrugApplyDetailEntity drugEntity : drugApplyDetailList) {
                            Map<String, String> reqMap = new HashMap<String, String>();
                            String inpatorderdataId = drugEntity.getInpatorderdataId();
                            Map<String, String> map = medicineApplyMapper.queryTmpPatientOrders(inpatorderdataId);
                            if (map != null) {
                                String primaryId = map.get("primaryId");
                                reqMap.put("primary_id", primaryId);
                                reqMap.put("org_id", drugEntity.getApplyDetailId());
                            }
                            ordersList.add(reqMap);
                        }
                        param.put("orders", ordersList);

                        Map<String, Object> requestMap = new HashMap<>();
                        requestMap.put("request", param);
                        Map<String, Object> params = new HashMap<>();
                        params.put("c_request", requestMap);
                        params.put("operationID", ConstantEnum.HIS_MEDICINE_APPLY_10008.getKey());
                        System.out.println(JSON.toJSONString(params));
                        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
                        if (jsonObject.isEmpty()) {
                            return ResultGenerator.genFailedResult("门诊领药删除失败");
                        }
                        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                        if (null != jsonObject) {
                            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                            if (resInt < 0) {
                                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                            }
                        }
                    }

                    //删除表中数据
                    Map<String, List<DrugApplyDetailDTO>> applyCollect = drugApplyDetailEntities.stream().collect(Collectors.groupingBy(e -> fetchGroupApplyId(e)));
                    List<String> applyList = new ArrayList<String>();
                    for (String key : applyCollect.keySet()) {
                        String applyId = key;
                        List<DrugApplyDetailDTO> drugApplyDetailList = applyCollect.get(key);
                        List<String> inpatorderdataIds = drugApplyDetailList.stream().map(drugDetail -> drugDetail.getInpatorderdataId()).collect(Collectors.toList());
                        medicineApplyMapper.deleteDrugApplyDetailByInpatorderdataId(inpatorderdataIds, "3", applyId);
                        List<DrugApplyDetailEntity> rest = medicineApplyMapper.queryDrugApplyDetailList(applyId);
                        if (CollectionUtils.isEmpty(rest)) {
                            applyList.add(key);
                        }
                    }
                    if (CollectionUtils.isNotEmpty(applyList)) {
                        medicineApplyMapper.updateDrugApplyMainByApplyIds("3", userId, applyList);
                    }
                }
            }
        }
        return ResultGenerator.genOkResult();
    }

    public void updateDrugApplyMainStatus() {
        List<String> applyList = medicineApplyMapper.queryDrugApplyMainByStatus();
        if (CollectionUtils.isNotEmpty(applyList)) {
            medicineApplyMapper.updateDrugApplyMainStatus(applyList);
            medicineApplyMapper.updateDrugApplyDetailStatus(applyList, "2");
        }
        List<String> list = medicineApplyMapper.queryDrugApplyMainByStatus4();
        if (CollectionUtils.isNotEmpty(list)) {
            medicineApplyMapper.updateDrugApplyDetailStatus(list, "4");
        }

    }


    public Result queryPatientPresc(String inpatNum,int page,int pageSize){
        PageHelper.startPage(page,pageSize);
        List<Map<String, String>> list = medicineApplyMapper.queryPatientPresc(inpatNum);
        PageInfo<Map<String, String>> pageInfo = new PageInfo<Map<String, String>>(list);
        return ResultGenerator.genOkResult(pageInfo);
    }

    public Result queryPatientPrescDetail(String prescNums){
        List<Map<String, String>> list = new CopyOnWriteArrayList<>();
        if(StringUtils.isNotBlank(prescNums)){
            String [] prescNumArray = prescNums.split(",");
            list = medicineApplyMapper.queryPatientPrescDetail(prescNumArray);
        }
        return ResultGenerator.genOkResult(list);
    }

    public Result noCompleteOrders(String inpatNum,String type,String orderId){
        //his接口
        List<Map<String, String>> resultList = new CopyOnWriteArrayList<>();
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("patient_id", inpatNum.split("-")[0]);
        param.put("visit_id", Integer.parseInt(inpatNum.split("-")[1]));
        param.put("operator", patientInHospitalMapper.queryPersonCodeByUserId(userId));
        param.put("operationdate", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
        param.put("query_type", Integer.parseInt(type));
        param.put("order_id", StringUtils.isNotBlank(orderId)?Integer.parseInt(orderId):"");
        requestMap.put("request", param);
        map.put("c_request", requestMap);
        map.put("operationID", ConstantEnum.HZQUERY_10022.getKey());
        log.info("HIS传参：:::::::::::::::::::::::::::::::::{}", map.toString());
        System.out.println(JSON.toJSONString(map));
        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, map);
        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
        if (null != jsonObject) {
            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
            if (resInt < 0) {
                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
            } else {
                if (jsonObject.getString("c_response") != null) {
                    Map<String, Object> cresponseMap = JSON.parseObject(jsonObject.getString("c_response"), new TypeReference<Map<String, Object>>() {
                    });
                    Map<String, Object> response = (Map<String, Object>) cresponseMap.get("response");
                    if (response != null && response.get("list") != null) {
                        List<Map<String, String>> list = (List<Map<String, String>>) response.get("list");
                        if(CollectionUtils.isNotEmpty(list)){
                            resultList = list;
                        }
                    }
                }
            }
        }
        return ResultGenerator.genOkResult(resultList);
    }

    public Result savePrescription(PrescApplyDTO prescApplyDTO){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        String nuserCode = patientInHospitalMapper.queryPersonCodeByUserId(userId);
        Date date = new Date();
        //主表数据
        List<PrescApplyMainDTO> mainList = prescApplyDTO.getPrescApplyMainDTOList();
        List<PrescApplyDetailDTO> detailList = prescApplyDTO.getPrescApplyDetailDTOList();
        if(CollectionUtils.isNotEmpty(mainList) && CollectionUtils.isNotEmpty(detailList)){
            mainList.stream().forEach(x->{
                List<PrescApplyDetailDTO> collect = detailList.stream().filter(y -> x.getPrescNum().equals(y.getPrescNum())).collect(Collectors.toList());
                x.setPrescApplyDetailDTOList(collect);
            });
        }
        //明细表数据
        //原本申请过，在勾选在保存 相当于重新保存一次
        //原本申请过，不勾选在保存 相当于取消申请
        List<Map<String, String>> list = new CopyOnWriteArrayList<>();
        //applyFlag 1 未申请  2已申请
        //区分未申请和已申请处方
        if(CollectionUtils.isNotEmpty(mainList)){
            //未勾选
            List<PrescApplyMainDTO> noSelectList = mainList.stream().filter(x -> "0".equals(x.getApplyFlag())).collect(Collectors.toList());
            //已勾选
            List<PrescApplyMainDTO> selectedList = mainList.stream().filter(x -> "1".equals(x.getApplyFlag())).collect(Collectors.toList());
            //List<PrescApplyMainDTO> insertSelectedList = mainList.stream().filter(x -> "1".equals(x.getApplyFlag())).collect(Collectors.toList());
            List<PrescApplyMainDTO> insertSelectedList = new CopyOnWriteArrayList<>();
            //已勾选 需要判断之前是否申请，如果申请过需要修改，没申请过需要新增
            if(CollectionUtils.isNotEmpty(selectedList)){
                String inpatNum = selectedList.get(0).getInpatNum();
                PatientInHospitalEntity patientInHospitalEntity = patientInHospitalMapper.selectPatientByInpatNum(selectedList.get(0).getInpatNum());
                List<String> prescNumList = selectedList.stream().map(PrescApplyMainDTO::getPrescNum).collect(Collectors.toList());
                //需要新增申请的处方
                List<String> insertPrescNumList = new CopyOnWriteArrayList<>();
                //需要修改申请时间的处方
                List<String> updatePrescNumList = new CopyOnWriteArrayList<>();
                List<Map<String, String>> updateList = new CopyOnWriteArrayList<>();
                if(CollectionUtils.isNotEmpty(prescNumList)) {
                    //申请过的处方
                    updateList = medicineApplyMapper.queryDrugApplyMainByReqId(prescNumList);
                    if (CollectionUtils.isNotEmpty(updateList)) {
                        updatePrescNumList = updateList.stream().map(x -> x.get("prescNum")).collect(Collectors.toList());
                        List<String> finalUpdatePrescNumList = updatePrescNumList;
                        insertPrescNumList = prescNumList.stream().filter(item -> !finalUpdatePrescNumList.contains(item)).collect(Collectors.toList());
                        if(CollectionUtils.isNotEmpty(insertPrescNumList)) {
                            List<PrescApplyMainDTO> finalInsertSelectedList = insertSelectedList;
                            insertPrescNumList.stream().forEach(x -> {
                                List<PrescApplyMainDTO> collect = selectedList.stream().filter(y -> x.equals(y.getPrescNum())).collect(Collectors.toList());
                                if(CollectionUtils.isNotEmpty(collect)){
                                    finalInsertSelectedList.add(collect.get(0));
                                }
                            });
                            insertSelectedList=finalInsertSelectedList;
                        }
                    }else{
                        insertPrescNumList = new CopyOnWriteArrayList<>(prescNumList);
                        insertSelectedList = selectedList;
                    }
                    String wardCode = patientInHospitalMapper.queryDeptCodeByDeptId(patientInHospitalEntity.getWardDeptId());
                    //处方处理本
                    //申请时间
                    //判断皮试
                    //处方主数据
                    List<Map<String, String>> prescMaster = new CopyOnWriteArrayList<>();
                    //处方明细数据
                    List<Map<String, String>> prescDetail = new CopyOnWriteArrayList<>();

                    if(CollectionUtils.isNotEmpty(insertSelectedList)){
                        for (PrescApplyMainDTO prescApplyMainDTO : insertSelectedList) {
                            List<PrescApplyDetailDTO> prescApplyDetailDTOList = prescApplyMainDTO.getPrescApplyDetailDTOList();
                            for (PrescApplyDetailDTO prescApplyDetailDTO : prescApplyDetailDTOList) {
                                Map<String, String> map = medicineApplyMapper.queryPatientPrescDrugInfo(prescApplyDetailDTO.getPrescdrugId());
                                if (map != null) {
                                    if (StringUtils.isNotBlank(map.get("testDrugFlag"))
                                            && "皮试".equals(map.get("testDrugFlag"))
                                            && "".equals(prescApplyDetailDTO.getPerformResult())) {
                                        return ResultGenerator.genFailedResult("请输入" + map.get("drugName") + "皮试结果后再保存!");
                                    } else if (StringUtils.isNotBlank(map.get("testDrugFlag"))
                                            && "皮试".equals(map.get("testDrugFlag"))
                                            && "(+)".equals(prescApplyDetailDTO.getPerformResult())) {
                                        return ResultGenerator.genFailedResult(map.get("drugName") + "皮试为阳性,请通知医师修改处方!");
                                    }
                                }
                                Map<String, String> prescDetailMap = new CopyOnWriteMap<>();
                                prescDetailMap.put("primary_id", prescApplyDetailDTO.getPrimaryId());
                                prescDetailMap.put("ps_result", prescApplyDetailDTO.getPerformResult());
                                prescDetail.add(prescDetailMap);
                            }
                            Map<String, String> prescMasterMap = new CopyOnWriteMap<>();
                            prescMasterMap.put("primary_id", prescApplyMainDTO.getPrimaryId());
                            prescMasterMap.put("performed_by", prescApplyMainDTO.getPerformedBy());
                            prescMaster.add(prescMasterMap);
                        }
                        Map<String, Object> param = new HashMap<>();
                        param.put("operator", nuserCode);
                        param.put("operationdate", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                        param.put("ward_code", wardCode);
                        param.put("patient_id", inpatNum.split("-")[0]);
                        param.put("visit_id", Integer.parseInt(inpatNum.split("-")[1]));

                        Map<String, Object> prescMap = new HashMap<>();
                        prescMap.put("presc_master", prescMaster);
                        prescMap.put("presc_detail", prescDetail);

                        param.put("presc", prescMap);

                        Map<String, Object> requestMap = new HashMap<>();
                        requestMap.put("request", param);
                        Map<String, Object> params = new HashMap<>();
                        params.put("c_request", requestMap);
                        params.put("operationID", ConstantEnum.HIS_MEDICINE_APPLY_10009.getKey());
                        System.out.println(JSON.toJSONString(params));
                        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
                        if (jsonObject.isEmpty()) {
                            return ResultGenerator.genFailedResult("处方处理本领药申请失败");
                        }
                        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                        if (null != jsonObject) {
                            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                            if (resInt < 0) {
                                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                            }
                        }
                    }
                }
                //更改申请时间
                /*if(CollectionUtils.isNotEmpty(updateList)){
                    medicineApplyMapper.updateDrugApplyMainInfo(updatePrescNumList,userId);
                    updateList.stream().forEach(x->{
                        String prescNum = x.get("prescNum");
                        List<PrescApplyMainDTO> collect = selectedList.stream().filter(y -> prescNum.equals(y.getPrescNum())).collect(Collectors.toList());
                        if(CollectionUtils.isNotEmpty(collect)){
                            List<PrescApplyDetailDTO> prescApplyDetailDTOList = collect.get(0).getPrescApplyDetailDTOList();
                            for(PrescApplyDetailDTO prescApplyDetailDTO:prescApplyDetailDTOList){
                                medicineApplyMapper.updateDrugApplyDetailInfo(prescApplyDetailDTO.getApplyDetailId(),userId,prescApplyDetailDTO.getPerformResult());
                            }
                        }

                    });
                }*/
                //新增申请数据
                List<DrugApplyMainDTO> drugApplyMainDTOS = new CopyOnWriteArrayList<>();
                if(CollectionUtils.isNotEmpty(insertSelectedList)){
                        insertSelectedList.stream().forEach(prescApplyMainDTO->{
                        List<DrugApplyDetailEntity> drugApplyDetailEntities = new CopyOnWriteArrayList<>();
                        List<PrescApplyDetailDTO> prescApplyDetailDTOList = prescApplyMainDTO.getPrescApplyDetailDTOList();
                        DrugApplyMainDTO drugApplyMainEntity = new DrugApplyMainDTO();
                        drugApplyMainEntity.setApplyId(UUIDUtil.randomString());
                        drugApplyMainEntity.initAdd();
                        drugApplyMainEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                        //申请时间
                        drugApplyMainEntity.setApplyTime(new Timestamp(date.getTime()));
                        drugApplyMainEntity.setApplyStatus("0");
                        drugApplyMainEntity.setType("2");
                        //his返回的申请号
                        drugApplyMainEntity.setReqId(prescApplyMainDTO.getPrescNum());
                        drugApplyMainEntity.setApplyPersonId(userId);
                        drugApplyMainEntity.setPharmacy(prescApplyMainDTO.getPharmacyId());
                        drugApplyMainEntity.setInpatNum(prescApplyMainDTO.getInpatNum());
                        drugApplyMainEntity.setBedNo(prescApplyMainDTO.getBedNo());
                        drugApplyMainEntity.setWardDeptId(patientInHospitalEntity.getWardDeptId());
                        drugApplyMainEntity.setPrescId(prescApplyMainDTO.getPrescId());
                        for (PrescApplyDetailDTO prescApplyDetailDTO : prescApplyDetailDTOList) {
                            DrugApplyDetailEntity drugApplyDetailEntity = new DrugApplyDetailEntity();
                            drugApplyDetailEntity.setApplyDetailId(UUIDUtil.randomString());
                            drugApplyDetailEntity.initAdd();
                            drugApplyDetailEntity.setHospitalId(StateEnum.HOSPITAL_ID.getValue());
                            drugApplyDetailEntity.setApplyId(drugApplyMainEntity.getApplyId());
                            drugApplyDetailEntity.setInpatNum(drugApplyMainEntity.getInpatNum());
                            drugApplyDetailEntity.setBedNo(drugApplyMainEntity.getBedNo());
                            drugApplyDetailEntity.setPrescdrugId(prescApplyDetailDTO.getPrescdrugId());
                            drugApplyDetailEntity.setPrescNum(prescApplyDetailDTO.getPrescNum());
                            drugApplyDetailEntity.setApplyStatus(drugApplyMainEntity.getApplyStatus());
                            drugApplyDetailEntity.setApplyTime(drugApplyMainEntity.getApplyTime());
                            drugApplyDetailEntity.setPerformResult(prescApplyDetailDTO.getPerformResult());
                            drugApplyDetailEntities.add(drugApplyDetailEntity);
                        }
                        drugApplyMainEntity.setDrugApplyDetailEntityList(drugApplyDetailEntities);
                        drugApplyMainDTOS.add(drugApplyMainEntity);
                    });

                    //新增数据
                    if (CollectionUtils.isNotEmpty(drugApplyMainDTOS)) {
                        for (DrugApplyMainDTO drugApplyMainDTO : drugApplyMainDTOS) {
                            medicineApplyMapper.insertDrugApplyMain(drugApplyMainDTO);
                            if (CollectionUtils.isNotEmpty(drugApplyMainDTO.getDrugApplyDetailEntityList())) {
                                //medicineApplyMapper.insertDrugApplyDetail(drugApplyMainDTO.getDrugApplyDetailEntityList());
                                int listSize = drugApplyMainDTO.getDrugApplyDetailEntityList().size();
                                int toIndex = 100;
                                for (int i = 0; i < drugApplyMainDTO.getDrugApplyDetailEntityList().size(); i += 100) {
                                    if (i + 100 > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                                        toIndex = listSize - i;
                                    }
                                    List newList = drugApplyMainDTO.getDrugApplyDetailEntityList().subList(i, i + toIndex);
                                    medicineApplyMapper.insertDrugApplyDetail(newList);
                                }
                            }
                        }
                    }
                }
            }
            //未勾选 需要判断之前是否申请 如果申请过需要删除
            if(CollectionUtils.isNotEmpty(noSelectList)){
                List<String> noPrescNumList = noSelectList.stream().map(PrescApplyMainDTO::getPrescNum).collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(noPrescNumList)){
                    //申请过的处方
                    List<Map<String, String>> deleteList = medicineApplyMapper.queryDrugApplyMainByReqId(noPrescNumList);
                    if(CollectionUtils.isNotEmpty(deleteList)){
                        Map<String,String> deleteMap = deleteList.get(0);
                        //处方处理(确认取消)
                        Map<String, Object> param = new HashMap<>();

                        param.put("operator", nuserCode);
                        param.put("operationdate", DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss"));
                        param.put("ward_code", patientInHospitalMapper.queryDeptCodeByDeptId(deleteMap.get("wardDeptId")));
                        param.put("performed_by", medicineApplyMapper.queryPharmacyCodeById(deleteMap.get("pharmacy")));
                        param.put("patient_id", deleteMap.get("inpatNum").split("-")[0]);
                        param.put("visit_id", Integer.parseInt(deleteMap.get("inpatNum").split("-")[1]));
                        List<Map<String,String>> prescMasterList = new CopyOnWriteArrayList<>();
                        deleteList.stream().forEach(x->{
                            Map<String, String> prescMap = new HashMap<String, String>();
                            prescMap.put("primary_id", x.get("primary_id"));
                            prescMasterList.add(prescMap);
                        });
                        Map<String, Object> prescMasterMap = new HashMap<String, Object>();
                        prescMasterMap.put("presc_master",prescMasterList);
                        param.put("presc", prescMasterMap);

                        Map<String, Object> requestMap = new HashMap<>();
                        requestMap.put("request", param);
                        Map<String, Object> params = new HashMap<>();
                        params.put("c_request", requestMap);
                        params.put("operationID", ConstantEnum.HIS_MEDICINE_APPLY_10010.getKey());
                        System.out.println(JSON.toJSONString(params));
                        JSONObject jsonObject = HttpClientUtil.sendPost(circulationUrl2, params);
                        if (jsonObject.isEmpty()) {
                            return ResultGenerator.genFailedResult("处方处理本领药删除失败");
                        }
                        log.info("HIS返回：：：：：：：：：：：：：：：：：：：：{}", JSONUtils.beanToJson(jsonObject));
                        if (null != jsonObject) {
                            Integer resInt = Integer.valueOf((String) jsonObject.get("Error_Id"));
                            if (resInt < 0) {
                                return ResultGenerator.genFailedResult(jsonObject.getString("Error_Msg"));
                            }
                        }

                        //删除申请数据
                        //逻辑删除
                        deleteList.stream().forEach(x->{
                            DrugApplyMainEntity drugApplyMainEntity = new DrugApplyMainEntity();
                            drugApplyMainEntity.setDeletePersonId(userId);
                            drugApplyMainEntity.setDeleteTime(new Timestamp(date.getTime()));
                            drugApplyMainEntity.setApplyStatus("3");
                            drugApplyMainEntity.setApplyId(x.get("applyId"));
                            medicineApplyMapper.updateDrugApplyMain(drugApplyMainEntity);
                            medicineApplyMapper.updateDrugApplyDetail(drugApplyMainEntity.getApplyId(), "3");
                        });
                    }
                }
            }
        }
        return ResultGenerator.genOkResult();
    }

    public Result confirmPatientPresc(String prescNums,String confirmFlag){
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getHeader("zuul_id");
        if(StringUtils.isNotBlank(prescNums)){
            String [] prescNumArray = prescNums.split(",");
            String personId = null;
            if("1".equals(confirmFlag)){
                personId = medicineApplyMapper.getPersonIdByUserId(userId);
            }
            medicineApplyMapper.updatePatientPresc(prescNumArray,personId);
            List<Map<String, String>> result = medicineApplyMapper.queryPatientPrescNurseId(prescNumArray);
            return ResultGenerator.genOkResult(result);
        }
        return ResultGenerator.genOkResult();
    }



    private static String fetchGroupInpatNum(Map<String, Object> map) {
        return String.valueOf(map.get("inpatNum"));
    }

    private static String fetchGroupKey(MedicineApplyDetailDTO medicineApplyDetailDTO) {
        return medicineApplyDetailDTO.getInpatNum();
    }

    private static String fetchGroupInpatNumAnd(MedicineApplyDetailDTO medicineApplyDetailDTO) {
        return medicineApplyDetailDTO.getInpatNum() + "#" + medicineApplyDetailDTO.getPharmacyId();
    }

    private static String fetchGroupInpatNumAndOrderNo(MedicineApplyDetailDTO medicineApplyDetailDTO) {
        return medicineApplyDetailDTO.getInpatNum() + "#" + medicineApplyDetailDTO.getOrderNo();
    }

    private static String fetchGroupInpatNumAndPrescId(MedicineApplyDetailDTO medicineApplyDetailDTO) {
        return medicineApplyDetailDTO.getInpatNum() + "#" + medicineApplyDetailDTO.getPrescId();
    }

    private static String fetchGroupInpatNums(DrugApplyDetailDTO drugApplyDetailDTO) {
        return drugApplyDetailDTO.getInpatNum();
    }

    private static String fetchGroupApplyId(DrugApplyDetailDTO drugApplyDetailDTO) {
        return drugApplyDetailDTO.getApplyId();
    }

}
